package com.zb.secure;

import cn.dev33.satoken.exception.SaTokenException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 *
 * @Author WEN
 * @Date 2023/11/1 0001
 **/
public class ZbSecureUtil {
    private static final Base64.Encoder encoder = Base64.getEncoder();
    private static final Base64.Decoder decoder = Base64.getDecoder();

    /**
     * AES加密
     * @param key
     * @param text
     * @return
     */
    public static String aesEncrypt(String key, String text) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] byteContent = text.getBytes(StandardCharsets.UTF_8);
            cipher.init(1, getSecretKey(key));
            byte[] result = cipher.doFinal(byteContent);
            return encoder.encodeToString(result);
        } catch (Exception var5) {
            throw (new SaTokenException(var5)).setCode(12114);
        }
    }

    /**
     * AES解密
     * @param key
     * @param text
     * @return
     */
    public static String aesDecrypt(String key, String text) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, getSecretKey(key));
            byte[] result = cipher.doFinal(decoder.decode(text));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception var4) {
            throw (new SaTokenException(var4)).setCode(12115);
        }
    }

    private static SecretKeySpec getSecretKey(String password) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kg.init(128, random);
        SecretKey secretKey = kg.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    }
}
